from flask import Flask, render_template, request,jsonify,escape
from panduan import panduan_login
from vsearch import search4letters
from pymysql import connect
from weatherapi import weather
import json
import requests


def look_over():
	con = connect(host="Ambersong.mysql.pythonanywhere-services.com",port=3306,user="Ambersong",password="sxt0525s",db="Ambersong$user")
	cursor1 = con.cursor()
	sql = "select * from student"
	cursor1.execute(sql)
	res = cursor1.fetchall()
	print(res)
	return res



app = Flask(__name__)

def log_request(req:"flask_request",res:str) -> None:
	with open("vsearch.log","a") as log:
		print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')

@app.route('/')
def hello() -> str:
	return "hello wrold"

@app.route('/search',methods=['POST'])
def search():
	phrase = request.form.get("phrase")
	letters = request.form.get("letters")
	title = "Here are your results"
	results = str(search4letters(phrase,letters))
	log_request(request,results)
	return render_template("results.html",the_title=title,the_phrase=phrase,the_letters=letters,the_results=results)

@app.route('/viewlog')
def view_the_log() -> str:
	with open("vsearch.log","r") as log:
		contents =[]
		for line in log:
			contents.append([])
			for item in line.split("|"):
				contents[-1].append(escape(item))
	title= ['Form data','Remote_addr','User_agent','Results']
	return render_template("view.html",the_title=title, the_data =contents)
	# return escape(contents)

@app.route('/login')
def login_page() -> 'html':
	return render_template('login.html',the_title ="欢迎您登录学生管理信息系统！")


@app.route('/xuanze',methods=['POST'])
def xuanze() -> 'html':
	zhanghao = request.form.get("zhanghao")
	mima = request.form.get("mima")
	a = panduan_login(zhanghao, mima)
	if a == "true":
		student_title = ["id","student_name","gender","class"]
		res=look_over()
		return render_template('xuanze.html',the_title ="登录成功，请您选择功能！",student_title=student_title,student_table=res)
	else:
		return "登录失败"


@app.route('/entry')
def entry_page() -> 'html':
	student_title = ["id","student_name","gender","class"]
	res=look_over()
	return render_template('entry.html',the_title ="欢迎您进入学生管理信息系统！",student_title=student_title,student_table=res)

@app.route('/deletestudent', methods=["POST"])
def delete_student() -> 'html':
	con = connect(host="Ambersong.mysql.pythonanywhere-services.com",port=3306,user="Ambersong",password="sxt0525s",db="Ambersong$user")
	cursor2 = con.cursor()
	student_id = request.form.get("deleteitem")
	sql = "delete from student where rewoid=%s"
	cursor2.execute(sql% student_id)
	con.commit()
	student_title = ["id","student_name","gender","class"]
	res=look_over()
	return render_template('entry.html',the_title ="welcome to searchletters on the web!",student_title=student_title,student_table=res)


@app.route("/xiugaistudent",methods=["POST"])
def modify_student():
	con = connect(host="Ambersong.mysql.pythonanywhere-services.com",port=3306,user="Ambersong",password="sxt0525s",db="Ambersong$user")
	cursor3 = con.cursor()
	student_id = request.form.get("additem")
	sql = "select * from student where rewoid=%s"%student_id
	cursor3.execute(sql)
	res= cursor3.fetchall()
	student_name= res[0][1]
	student_gender=res[0][2]
	student_class=res[0][3]
	return render_template("xiugaistudent.html",student_id=student_id,student_name=student_name,student_gender=student_gender,student_class=student_class)


@app.route('/xiugai',methods=["POST"])
def modify_page() -> 'html':
	con = connect(host="Ambersong.mysql.pythonanywhere-services.com",port=3306,user="Ambersong",password="sxt0525s",db="Ambersong$user")
	cursor4 = con.cursor()
	student_id = request.form.get("student_id")
	student_name = request.form.get("student_name")
	student_gender = request.form.get("student_gender")
	student_class = request.form.get("student_class")
	sql = "update student set name='%s',gender='%s',class='%s' where rewoid='%s'"% (student_name,student_gender,student_class,student_id)
	print(sql)
	cursor4.execute(sql)
	con.commit()
	return render_template("modifysecesspage.html")

@app.route('/addstudentpage',methods=["GET"])
def addstudent_page() -> "html":
	return render_template("addstudentpage.html")


@app.route('/addstudent',methods=["POST"])
def add_student():
	con = connect(host="Ambersong.mysql.pythonanywhere-services.com",port=3306,user="Ambersong",password="sxt0525s",db="Ambersong$user")
	cursor5 = con.cursor()
	student_id = request.form.get("student_id")
	student_name = request.form.get("student_name")
	student_gender = request.form.get("student_gender")
	student_class = request.form.get("student_class")
	sql = "insert into student set rewoid='%s', name='%s',gender='%s',class='%s'"% (student_id, student_name,student_gender,student_class)
	cursor5.execute(sql)
	con.commit()
	return render_template("addsucesspage.html")

@app.route('/findstudent',methods=["POST"])
def find_student():
	con = connect(host="Ambersong.mysql.pythonanywhere-services.com",port=3306,user="Ambersong",password="sxt0525s",db="Ambersong$user")
	cursor6 = con.cursor()
	student_gender = request.form.get("student_gender")
	student_class = request.form.get("student_class")
	print(student_gender,student_class)
	if student_gender!='' and student_class=='':
		sql = "select * from student where gender='%s'"% (student_gender)
	elif student_gender=='' and student_class!='':
		sql = "select * from student where class='%s'"% (student_class)
	elif student_gender!='' and student_class!='':
		sql = "select * from student where gender='%s' and class='%s'"% (student_gender,student_class)
	else:
		sql = "select * from student"
	cursor6.execute(sql)
	res = cursor6.fetchall()
	student_title = ["id","student_name","gender","class"]
	return render_template("entry.html",the_title ="登录成功，欢迎您进入学生管理信息系统！",student_title=student_title,student_table=res)


@app.route('/results',methods = ['GET'])
def results_page() -> 'html':
	return render_template('results.html',the_title ="welcome to searchletters on the web!")



#进行调色
@app.route("/change")
def hello_enrty() ->"html":
	return render_template("color.html",the_title="调色网站")

@app.route("/color",methods=["POST"])
def color():
	col = request.form["col"]
	return render_template("color.html",the_col = col)


#茂名天气
@app.route("/tianqi",methods=["post"])
def tianqi():
	key='030d60847cc2dbf652a0d1f7e0fce690'
	city='440900'
	extensions='base'
	a=weather(key,city,extensions)
	b=a['lives'][0]['city']
	c=a['lives'][0]['weather']
	d=a['lives'][0]['temperature']
	return render_template('weather.html',city=str(b),weather=str(c),temperature=str(d))



if __name__ == '__main__':
	app.run(debug = True)